var docedit_submit_link = webrootpath+"doc/docedit_submit_link";
var upload_file = webrootpath+"file/upload_file";

var upload_ueditor_file = webrootpath+"file/upload_ueditor_file";
var initupdatedoc_link = webrootpath+"doc/initupdatedoc_link";

var delAttached_link = webrootpath+"doc/delAttached_link";
var model_indexlm_selectbianlianglink = webrootpath+"lm/model_indexlm_selectbianlianglink";//查询文档概要属性信息

var ue_editor;

var istemplate = 1;//是否启用配置模板
$(function () {

    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function(action) {
        console.log(action);
        if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage') {
            return upload_ueditor_file;
        } else if (action == 'uploadvideo') {
            return upload_ueditor_file;
        } else if(action == 'config'){
            return upload_ueditor_file;
        }else {
            return this._bkGetActionUrl.call(this, action);
        }
    }
    ue_editor = UE.getEditor('doc_container',{
        initialFrameHeight:400
    });
    model_indexlm_selectbianliang();
    loadUplad();
    loadUplad_pic();
    initupdatedoc();


});

/**
 * 查询当前栏目下的数据
 */
function model_indexlm_selectbianliang() {
    var selectlmid = sessionStorage.getItem("selectlmid");
    $.get(model_indexlm_selectbianlianglink,{
        selectcateid:selectlmid
    },function (_info) {
        if(_info.code=="1"){
            istemplate = 2;
            $("#docedit_zhaiyao_2").show();
            $("#docedit_zhaiyao_1").hide();
            var datalist = _info.data;
            var htmlstr = "";
            for(var i in datalist){
                var dataobj = datalist[i];
                htmlstr +="<div class=\"form-group\" style='padding: 10px;border-bottom: thin dashed;'>\n" +
                                "<label for=\"firstname\" class=\"col-sm-2 control-label\">"+dataobj.propertiesname+"</label>\n" +
                                "<div class=\"col-sm-10\">\n" +
                                "<textarea class=\"form-control\"></textarea>" +
                                "</div>\n" +
                           "</div>";
            }
            htmlstr = "<form class=\"form-horizontal\" role=\"form\">"+htmlstr+"</form>";
            $("#docedit_zhaiyao_2").html(htmlstr);
        }else {
            istemplate = 1;
            $("#docedit_zhaiyao_1").show();
            $("#docedit_zhaiyao_2").hide();
        }
    });
}

/***
 *  删除附件
 */
function delAttached(attachedid) {
    $.confirm({
        title:"提示",
        content:"您确认删除此附件吗？",
        buttons:{
            "确定":function () {
                $.get(delAttached_link,{attachedid:attachedid},function (msg) {
                    if (msg.code=='1'){
                        $("#att"+attachedid).remove();
                        $.confirm({
                            title: '提示',
                            content: '成功删除附件！',
                            autoClose: '确定|2000',
                            buttons: {
                                确定: {
                                }
                            }
                        });
                    }
                });
            },
            "取消":function () {





            }
        }
    });
}

/****
 * 初始化编辑文档内容
 */
function initupdatedoc() {
    var selectlmid = sessionStorage.getItem("selectlmid");
    var updatedocid = sessionStorage.getItem("updatedocid");
    if (selectlmid==undefined || updatedocid==undefined){
        return false;
    }
    if(updatedocid==-1){
        return false;
    }
    $.get(initupdatedoc_link,{selectlmid:selectlmid,updatedocid:updatedocid},function (content) {
        if(content.code=='1'){
            var docobj = content.data;
            $("#docedit_biaoti").val(docobj.docname);

            if(istemplate==1){
                $("#docedit_zhaiyao").val(docobj.docabstract);
            }else if(istemplate==2){
                var dataobjlist = JSON.parse(docobj.docabstract);
                for(var obj in dataobjlist){
                    var objval = dataobjlist[obj];
                    $("#docedit_zhaiyao_2").find(".form-group").each(function (_index,_this) {
                        var key_str = $.trim($(_this).find("label").text());
                        if(key_str==obj){
                            $(_this).find("textarea").val(objval);
                        }
                    });
                }
            }

            setTimeout(function () {
                ue_editor.setContent(docobj.dochtmlcontent);
            },1000);
            var attachedhtml = "";
            var attachedlist = content.attachedlist;
            if (attachedlist!=undefined && attachedlist.length>0){
                for(var i in attachedlist){
                    var attobj = attachedlist[i];
                    attachedhtml+="<tr id=\"att"+attobj.attachedid+"\">"+
                                        "<td>"+attobj.attachedtruename+"<input name='att_name' value='"+attobj.attachedid+"' style='display: none;' /></td>"+
                                        "<td>"+attobj.attachedsize+"</td>"+
                                        "<td><span class=\"label label-danger\" style='cursor: pointer;'  onclick=\"delAttached('"+attobj.attachedid+"')\">删除</span></td>"+
                                    "</tr>";
                }
            }
            $("#thelist_uploadfile").html(attachedhtml);
        }
    });
}




/***
 * 内容提交
 */
function docedit_submit() {

    var updatedocid = sessionStorage.getItem("updatedocid");

    var selectlmid = sessionStorage.getItem("selectlmid");
    var docedit_biaoti = $.trim($("#docedit_biaoti").val());
    var docedit_zhaiyao = $.trim($("#docedit_zhaiyao").val());
    var docedit_content = $.trim(ue_editor.getContentTxt());
    var docedit_htmlcontent = $.trim(ue_editor.getContent());

    var att_name_list = "";
    $("input[name='att_name']").each(function (_index,_this) {
        att_name_list+=","+_this.value;
    });

    if (docedit_biaoti==""){
        alert("标题不能为空");
        return false;
    }
    if (selectlmid=="" || selectlmid==undefined){
        alert("没有选择栏目");
        return false;
    }
    if(istemplate==1){
        //不启用配置模板

    }else if(istemplate==2){
        //启用配置模板
        var abstr = "";
        $("#docedit_zhaiyao_2").find(".form-group").each(function (_index,_this) {
            var key_str = $.trim($(_this).find("label").text());
            var val_str = $.trim($(_this).find("textarea").val());
            abstr+=","+JSON.stringify(key_str)+":"+JSON.stringify(val_str);
        });
        if(abstr!=""){
            abstr = abstr.substring(1);
            abstr = "{"+abstr+"}";
        }
        docedit_zhaiyao = abstr;
    }
    $.ajax({
        type:"post",
        url:docedit_submit_link,
        data:{
            updatedocid:updatedocid,
            selectlmid:selectlmid,
            docedit_biaoti:docedit_biaoti,
            docedit_zhaiyao:docedit_zhaiyao,
            docedit_content:docedit_content,
            docedit_htmlcontent:docedit_htmlcontent,
            att_name_list:att_name_list
        },
        cache:false,
        async:false,
        success:function (msg) {
            if (msg.code=='1'){
                window.opener.getdoclistbylmid(selectlmid,1);
                var as = $.confirm({
                    title: '提示',
                    content: '操作成功，关闭页面',
                    autoClose: '关闭|3000',
                    buttons: {
                        "关闭": function () {
                            as.close();
                            window.close();
                        }
                    }
                });
            }else {
                alert("操作失败");
                return false;
            }
        }
    });
}

/***
 * 格式化摘要
 */
function gshZY(_this) {
    $('#json-renderer').jsonViewer("");
    var zycontent = $("#docedit_zhaiyao").val();

    try {
        var parsezycontent = JSON.parse(zycontent);
    }catch (e){
        alert("验证未通过："+e);
    }
    $('#json-renderer').show();
    $('#json-renderer').jsonViewer(parsezycontent, {collapsed: false, withQuotes: true, withLinks: false});
}


/***
 * 加载文件
 */
function  loadUplad() {
    $("#thelist_uploadfile").html("");
    $("#thelist").html("");
    var uploader = WebUploader.create({
        swf: './webuploader-0.1.5/Uploader.swf',
        auto:true,
        server: upload_file,
        pick: '#picker',
        resize: false,
        fileNumLimit:1,
        formData:{
            filetype:10
        },
        accept:{
            title: '选择文件',
            extensions: '*',
            mimeTypes: 'application/*;audio/*;video/*;text/*'
        },
        fileSizeLimit:10485760000
    });
    uploader.on( 'fileQueued', function( file ) {

        $("#thelist").html( '<div id="' + file.id + '" class="item">' +
            '<h4 class="info">' + file.name + '</h4>' +
            '<p class="state">等待上传...</p>' +
            '</div>' );
    });
    uploader.on( 'beforeFileQueued', function( file ) {
        uploader.reset();
    });

    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');

        if ( !$percent.length ) {
            $percent = $('<div class="progress progress-striped active">' +
                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                '</div>' +
                '</div>').appendTo( $li ).find('.progress-bar');
        }

        $li.find('p.state').text('上传中并正在处理，请稍等！！！');
        $percent.css( 'width', percentage * 100 + '%' );
    });
    //上传成功
    uploader.on( 'uploadSuccess', function( file,response ) {
        $( '#'+file.id ).find('p.state').text('上传完毕');
        setTimeout(function(){
            $("#thelist").html("");
            if(response.code=='1'){
                var htmlstr = "<tr id=\"att"+response.data.attachedid+"\" >"+
                                "<td>"+response.data.truename+"<input name='att_name' value='"+response.data.attachedid+"' style='display: none;' /></td>"+
                                "<td>"+response.data.size+"</td>"+
                                "<td><span class=\"label label-danger\" style='cursor: pointer;'  onclick=\"delAttached('"+response.data.attachedid+"')\">删除</span></td>"+
                                "</tr>";

                $("#thelist_uploadfile").append(htmlstr);
            }

            uploader.reset();
        },1000);
    });
    uploader.on( 'uploadError', function( file ) {
        $( '#'+file.id ).find('p.state').text('上传出错');
    });
    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
    });
    $("#ctlBtn").click(function () {
        truenames = $("#thelist").find(".info").text();
        uploader.upload();
    });
}

/***
 * 加载图片类型图片
 */
function  loadUplad_pic() {
    $("#thelist_uploadfile").html("");
    $("#thelist").html("");
    var uploader = WebUploader.create({
        swf: './webuploader-0.1.5/Uploader.swf',
        auto:true,
        server: upload_file,
        pick: '#picker_pic',
        resize: false,
        fileNumLimit:1,
        formData:{
            filetype:20
        },
        accept:{
            title: '选择图片',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        },
        fileSizeLimit:10485760000
    });
    uploader.on( 'fileQueued', function( file ) {

        $("#thelist").html( '<div id="' + file.id + '" class="item">' +
            '<h4 class="info">' + file.name + '</h4>' +
            '<p class="state">等待上传...</p>' +
            '</div>' );
    });
    uploader.on( 'beforeFileQueued', function( file ) {
        uploader.reset();
    });

    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');

        if ( !$percent.length ) {
            $percent = $('<div class="progress progress-striped active">' +
                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                '</div>' +
                '</div>').appendTo( $li ).find('.progress-bar');
        }

        $li.find('p.state').text('上传中并正在处理，请稍等！！！');
        $percent.css( 'width', percentage * 100 + '%' );
    });
    //上传成功
    uploader.on( 'uploadSuccess', function( file,response ) {
        $( '#'+file.id ).find('p.state').text('上传完毕');
        setTimeout(function(){
            $("#thelist").html("");
            if(response.code=='1'){
                var htmlstr = "<tr id=\"att"+response.data.attachedid+"\" >"+
                    "<td>"+response.data.truename+"<input name='att_name' value='"+response.data.attachedid+"' style='display: none;' /></td>"+
                    "<td>"+response.data.size+"</td>"+
                    "<td><span class=\"label label-danger\" style='cursor: pointer;'  onclick=\"delAttached('"+response.data.attachedid+"')\">删除</span></td>"+
                    "</tr>";

                $("#thelist_uploadfile").append(htmlstr);
            }

            uploader.reset();
        },1000);
    });
    uploader.on( 'uploadError', function( file ) {
        $( '#'+file.id ).find('p.state').text('上传出错');
    });
    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
    });
    $("#ctlBtn").click(function () {
        truenames = $("#thelist").find(".info").text();
        uploader.upload();
    });
}